package ro.sobis.repetor;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class InregistrareClient implements Runnable {

	private Log log = LogFactory.getLog(InregistrareClient.class);
	private Socket socketClient;
	private Thread t ;
	private InputStream inputStream;
	private String numeServer;
	public InregistrareClient(Socket s) {

		socketClient =s;

		try{
			inputStream = socketClient.getInputStream();
		}catch(IOException e)
		{
			log.error(e.getMessage());
		}

		t= new Thread(this);
		t.start();


	}

	@Override
	public void run() {
		int bufLen=512;
		byte buf[]= new byte[bufLen];
		int bytesCititi;

		while(true)
		{
			try
			{
				bytesCititi = inputStream.read(buf, 0, bufLen);
				if(bytesCititi>0)
				{

					byte encServerName [] = new byte[bytesCititi];
					System.arraycopy(buf, 0, encServerName, 0, bytesCititi);
					EncryptDecrypt ed = new EncryptDecrypt();
					numeServer= ed.decrypt(encServerName);
					Repetor.getClienti().put(numeServer, socketClient);
					log.info("Client nou conectat: "+numeServer);
				}
				else
					if(bytesCititi < 0) {

						Repetor.getClienti().remove(numeServer);
						log.info("Client deconectat: "+numeServer);
						return ;
					}
					else {
						log.error("Socket-ul a returnat 0 bytes in loc sa ramana blocat..."+socketClient);
						return;
					}

			}
			catch(Exception ex)
			{
				Repetor.getClienti().remove(numeServer);
				log.error(ex.getMessage());
				return;
			}

		}

	}

}
